<template>
  <el-dialog width="80%" @close="onClose" @open="onOpen" :model-value="visible" class="map-dialog">
    <div
      id="map"      
      class="map-container"      
    >
    </div>
  </el-dialog>
</template>

<script lang="ts" setup>
import type { Location } from '@/api/pass/passModel'
import { usePassStore } from '@/store/modules/pass';


defineProps(['visible'])
const emit = defineEmits(['update:visible'])
const { addLocation } = usePassStore()

function onClose() {
  emit('update:visible', false)
}

function onOpen() {  
  initMap();
}

const latlng = ref<Location>({ latitude: -25.363, longitude: 131.044 })

let map: google.maps.Map;
async function initMap(): Promise<void> {  
  const { Map } = await google.maps.importLibrary("maps") as google.maps.MapsLibrary;
  map = new Map(document.getElementById("map") as HTMLElement, {
    center: { lat: latlng.value.latitude, lng: latlng.value.longitude },
    zoom: 4,
  });

  let infoWindow = new google.maps.InfoWindow({
    content: "",
    position: { lat: latlng.value.latitude, lng: latlng.value.longitude },
  });
  

  map.addListener("click", (mapsMouseEvent) => {    
    return function (mapsMouseEvent, closeEvent) {      
      const json = mapsMouseEvent.latLng.toJSON()
      infoWindow.close();
      
      infoWindow = new google.maps.InfoWindow({
        position: mapsMouseEvent.latLng,
      });
      infoWindow.setContent(      
        `
          <div>Longitude: ${json.lng}<br/>Latitude: ${json.lat}</div>
          <div style="text-align: center; padding: 8px 0">
          <button class="el-button el-button--primary" id="SelectButton"><span>Select</span></button>
          </div>
        `     
      );      
      latlng.value = { longitude: json.lng, latitude: json.lat }

      infoWindow.open(map);
      nextTick(() => {
        const button = document.getElementById('SelectButton')
        button?.addEventListener('click', () => {
          addLocation(latlng.value)
          onClose()
        })
      })
    }(mapsMouseEvent, onClose)
  });
}

</script>

<style lang="scss">
  .map-dialog {
    .map-container {  
      position: absolute;
      top: 0;
      bottom: 0px;
      width: 100%;
      height: 80vh;
      right: 0px;
      left: 0px;
      z-index: 1;      
    }
    .el-dialog__header {
      height: 0;
      padding: 0;
      .el-dialog__headerbtn {
        top: -25px;
        right: -46px;
        width: 24px;
      }
      .el-dialog__headerbtn.is-text:hover {
        background-color: transparent;
      }
      .el-dialog__headerbtn .el-icon.el-dialog__close {
        font-size: 24px;
        color: #fff9;        
        transition-duration: .15s;
        display: inline-block;
        transition-property: transform,color;
        &:hover {
          color: #ffffff;
          cursor: pointer;
          transform: scale(1.2);
        }
      }
    }

  }
</style>

<style lang="scss" scoped>
    
</style>